﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using JScriptSuite.QA.Lib;
using JScriptSuite.InteropServices;

namespace JScriptSuite.QA.App
{
    public class ResultItem
    {
        readonly object[] items;
        readonly ResultItem[] children;
        readonly string tag;

        ResultItem(JResultItem source, Func<object, object> unwrapper)
        {
            tag = source.Tag;
            items = new object[source.Items.Length];
            for (int i = 0; i < items.Length; i++)
            {
                object value = source.Items.Get<object>(i);
                value = unwrapper(value);
                JDate jdate = value as JDate;
                if (jdate != null)
                {
                    value = new DateTime(jdate.Year, jdate.Month + 1, jdate.Date, jdate.Hours, jdate.Minutes, jdate.Seconds, jdate.Milliseconds);
                }

                items[i] = value;
            }

            children = new ResultItem[source.Children.Length];
            for (int i = 0; i < children.Length; i++)
            {
                children[i] = Query(source.Children.Get<JResultItem>(i), unwrapper);
            }
        }

        public static ResultItem Query(JResultItem source, Func<object, object> unwrapper)
        {
            return source != null ? new ResultItem(source, unwrapper) : null;
        }

        public string Tag
        {
            get
            {
                return tag;
            }
        }

        public object[] Items
        {
            get
            {
                return items;
            }
        }

        public ResultItem[] Children
        {
            get
            {
                return children;
            }
        }

    }
}
